package com.yxjme.redpackagelibrary;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;

public class RedPacketView extends View {

    //红包图片
    private int[] mImgIds = new int[]{R.mipmap.icon_jinbi,R.mipmap.icon_jinbi1};
    //红包数量
    private int count;
    //下落速度
    private int speed;
    //红包大小的范围
    private float maxSize;
    //红包大小的范围
    private float minSize;
    //view宽度
    private int mWidth;
    //属性动画，用该动画来不断改变红包下落的坐标值
    private ValueAnimator animator;
    //画笔
    private Paint paint;
    private long prevTime;
    /**
     * 总红包数量
     */
    private List<RedPacket> allList = new ArrayList<>();
    /**
     * 当前撒的红包数量
     */
    private ArrayList<RedPacket> redpacketlist = new ArrayList<>();//红包数组


    public RedPacketView(Context context) {
        super(context);
        init();
    }


    public RedPacketView(Context context, AttributeSet attrs) {
        super(context, attrs);
        final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RedPacketStyle);
//        count = typedArray.getInt(R.styleable.RedPacketStyle_count, 20);
        speed = typedArray.getInt(R.styleable.RedPacketStyle_speed, 20);
        minSize = typedArray.getFloat(R.styleable.RedPacketStyle_min_size, 0.4f);
        maxSize = typedArray.getFloat(R.styleable.RedPacketStyle_max_size, 1.2f);
        typedArray.recycle();
        init();
    }




    /**
     * 下落的速度
     * @param speed
     */
    public void setSpeed(int speed) {
        this.speed = speed;
    }


    /**
     * 初始化
     */
    private void init() {
        paint = new Paint();
        paint.setFilterBitmap(true);
        paint.setDither(true);
        paint.setAntiAlias(true);
        animator = ValueAnimator.ofFloat(0, 1);
        setLayerType(View.LAYER_TYPE_HARDWARE, null);
        initAnimator();
    }



    private void initAnimator() {
        //每次动画更新的时候，更新红包下落的坐标值
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                long nowTime = System.currentTimeMillis();
                float secs = (float) (nowTime - prevTime) / 1000f;
                prevTime = nowTime;
                /*写死固定值*/
                secs = 0.01f;

                /*循环下落固定的红包*/
                for (int i = 0; i < redpacketlist.size(); ++i) {
                    RedPacket redPacket = redpacketlist.get(i);
                    //如果y坐标大于view的高度 说明划出屏幕，y重新设置起始位置，以及中奖属性
                    if (redPacket!=null&&redPacket.y < getHeight()) {
                        //更新红包的下落的位置y
                        redPacket.y += (redPacket.speed * secs);
                        //更新红包的旋转的角度
                        redPacket.rotation = redPacket.rotation + (redPacket.rotationSpeed * secs);
                    }
                }
                /*不断重新绘制*/
                invalidate();
            }
        });
        //属性动画无限循环
        animator.setRepeatCount(ValueAnimator.INFINITE);
        //属性值线性变换
        animator.setInterpolator(new LinearInterpolator());
        animator.setDuration(1);
    }


    /**
     * 倒计时时间  秒
     */
    private int timeSeconds = 30 ;
    public void setTimeSeconds(int timeSeconds) {
        this.timeSeconds = timeSeconds;
    }


    /**
     * 是否正在下红包雨
     */
    private boolean isRunning ;
    public boolean isRunning() {
        return isRunning;
    }


    /**
     * 不停撒红包  知道红包撒完
     *
     */
    private void sprinkleRedPackage(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (allList.size()>0){
                    isRunning = true ;
                    if (isCanSprinkleRed()){
                        redpacketlist.add(allList.get(0));
                        allList.remove(0);
                    }
                }

                Iterator<RedPacket> it = redpacketlist.iterator();
                while (it.hasNext()){
                    RedPacket p = it.next();
                    if (p!=null&&p.y>getHeight()){
                        p.recycle();
                        it.remove();
                    }
                }
                isRunning = false ;
            }
        }).start();
    }


    private long lastTime;

    /**
     * 是否可撒红包
     *
     * @return
     */
    private boolean isCanSprinkleRed(){
        /*投放每一个的时间*/
        long speedTime = timeSeconds*1000/count - 2;
        if ((System.currentTimeMillis() -lastTime) > speedTime){
            lastTime = System.currentTimeMillis();
            Log.v("======allList======","size="+allList.size());
            return true;
        }
        return false;
    }



    /**
     *停止动画
     */
    public void stopRainNow() {
        //清空红包数据
        reset();
        //动画取消
        animator.cancel();
    }



    /**
     * 开始动画
     */
    public void startRain() {
        prevTime = System.currentTimeMillis();
        //动画开始
        animator.start();
        /*实时撒红包*/
        sprinkleRedPackage();
    }




    /**
     * 测试
     */
    private boolean isTest;
    public void setTest(boolean test,int c) {
        isTest = test;
        /*测试红包*/
        testRedPackage(c);
    }



    /**
     * @param count
     */
    private void testRedPackage(int count) {
        if (isTest){
            this.count = count;
            reset();
            for (int i = 0; i < count; ++i) {
                //获取红包原始图片
                Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), mImgIds[new Random().nextInt(2)]);
                //生成红包实体类
                RedPacket redPacket = new RedPacket(getContext(),
                        originalBitmap,
                        UUID.randomUUID().toString(),
                        new Random().nextInt(100),
                        speed,
                        mWidth,
                        minSize,
                        maxSize);
                //添加进入红包数组
                allList.add(redPacket);
            }
        }
    }



    /**
     *
     * 設置数据源
     *
     * @param list
     */
    public void setData(ArrayList<RedPacket> list){
        reset();
        this.count = list!=null ? list.size() : 0;
        allList.addAll(list);
    }



    /**
     * 暂停红包雨
     */
    public void pauseRain() {
        animator.cancel();
    }



    /**
     * 重置
     */
    public void reset(){

        clear();

        allList.clear();
        //重绘
        invalidate();
    }



    /**
     * 重新开始
     */
    public void restartRain() {
        animator.start();
    }



    /**
     * 清空红包数据，并回收红包中的bitmap
     */
    private void clear() {
        for (RedPacket redPacket :redpacketlist) {
            redPacket.recycle();
        }
        redpacketlist.clear();
    }



    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取自定义view的宽度
        mWidth = getMeasuredWidth();
    }

    @Override
    protected void onDraw(final Canvas canvas) {
        //遍历红包数组，绘制红包
        for (int i = 0; i < redpacketlist.size(); i++) {
            RedPacket redPacket = redpacketlist.get(i);
            if (redPacket!=null){
                if (redPacket.y < getHeight()){
                    //将红包旋转redPacket.rotation角度后 移动到（redPacket.x，redPacket.y）进行绘制红包
                    Matrix m = new Matrix();
                    m.setTranslate(-redPacket.width / 2, -redPacket.height / 2);
                    m.postRotate(redPacket.rotation);
                    m.postTranslate(redPacket.width / 2 + redPacket.x, redPacket.height / 2 + redPacket.y);
                    //绘制红包
                    canvas.drawBitmap(redPacket.bitmap, m, paint);
                }else {
                    redPacket.recycle();
                }
            }
        }
    }


    /**
     * 是否支持点击消失
     */
    private boolean isSupportClickDisappear ;
    public void setSupportClickDisappear(boolean b){
        this.isSupportClickDisappear = b;
    }


    @Override
    public boolean onTouchEvent(MotionEvent motionEvent) {
        switch (motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
                //根据点击的坐标点，判断是否点击在红包的区域
                RedPacket redPacket = isRedPacketClick(motionEvent.getX(), motionEvent.getY());
                if (redPacket != null) {
                    //如果点击在红包上，重新设置起始位置，以及中奖属性
//                    redPacket.y = 0 - redPacket.height;
//                    redPacket.isRealRed = redPacket.isRealRedPacket();
                    if (isSupportClickDisappear){
                        redPacket.y = getHeight()+redPacket.height;
                    }

                    if (list.size()<=5){
                        MediaPlayer mMediaPlayer = MediaPlayer.create(getContext(),R.raw.ring2);
                        mMediaPlayer.start();
                        list.add(mMediaPlayer);
                        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {
                                list.remove(mediaPlayer);
                                mediaPlayer.stop();
                                mediaPlayer.release();
                            }
                        });
                    }


                    if (onRedPacketClickListener != null) {
                        onRedPacketClickListener.onRedPacketClickListener(redPacket,motionEvent);
                    }
                }
                break;
        }
        return true;
    }


    private List<MediaPlayer> list = new ArrayList<>() ;


    //根据点击坐标点，遍历红包数组，看是否点击在红包上
    private RedPacket isRedPacketClick(float x, float y) {
        for (int i = redpacketlist.size() - 1; i >= 0; i --) {
            if (redpacketlist.get(i).isContains(x, y)) {
                return redpacketlist.get(i);
            }
        }
        return null;
    }





    public interface OnRedPacketClickListener {
        void onRedPacketClickListener(RedPacket redPacket,MotionEvent motionEvent);
    }



    private OnRedPacketClickListener onRedPacketClickListener;
    public void setOnRedPacketClickListener(OnRedPacketClickListener onRedPacketClickListener) {
        this.onRedPacketClickListener = onRedPacketClickListener;
    }
}
